<template>
  <el-card shadow="never" class="aui-card--fill">
    <div>
      <el-form :inline="true" :model="dataForm"  @keydown.enter.native.prevent="searchNotice()">
        <el-form-item>
          <el-input v-model="dataForm.describe" placeholder="主题/创建者/内容" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="searchNotice()">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="dataListLoading" highlight-current-row :data="showDataList"  @refreshDataList="getDataList" 
       
        border
        @selection-change="dataListSelectionChangeHandle"  style="width: 100%;">
        <el-table-column prop="noticeTopic" label="公告主题"  header-align="center" align="center"  
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-badge v-if="scope.$index<3" :value="hot" class="hotItem">
              <el-button type="text" size="mini" v-html="showDate(scope.row.noticeTopic)"
                @click="childHandle(scope.row)">
              </el-button>
            </el-badge>
            <el-badge v-if="scope.$index>=3" value="" class="hotItem">
              <el-button type="text" size="mini" v-html="showDate(scope.row.noticeTopic)" @click="childHandle(scope.row)">
              </el-button>
            </el-badge>
            
          </template>
        </el-table-column>
        <el-table-column prop="noticeContent" label="公告内容"  header-align="center" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span type="text" size="small" v-html="showDateC(scope.row.noticeContent)">
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createby" label="创建者"  header-align="center" align="center" width="100">
          <template slot-scope="scope">
            <span type="text" size="small" v-html="showDate(scope.row.createby)">
            
            </span>
          </template>
          
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间"  header-align="center" align="center" width="100"></el-table-column>
        
          <!-- fixed="right" -->
      </el-table>
      <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total"
        layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle"
        @current-change="pageCurrentChangeHandle">
      </el-pagination> 
      <!-- 弹窗, 新增 / 修改-->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
  </el-card>
</template>

<script>
// import AddOrUpdate from './notice-add-or-update.vue'
import { addDynamicRoute } from '@/router'
import servicesApi from '@/services/servicesApi'
export default {
  data() {
    return {
      hot: 'hot',
      index: 1,
      dataForm: {
        id: 0,
        describe: null,
      },               // 查询条件
      showDataList: [],
      dataList: [
        {
          id: 11,
          userId: 0,
          createby: '李西茵',
          username: '2020110228',
          target: 0, //0全体用户，1学生,2教师
          noticeTopic: '关于毕设答辩的通知',
          noticeContent: '',
          createtime: '',
          gmtCreate: '2022-12-10 21:14:10',
          gmtModified: '2022-12-10 21:14:10',
          createDate: '',
          version: 0,
          deleted: 0,
        },
      ],               // 数据列表
      order: '',                  // 排序，asc／desc
      orderField: '',             // 排序，字段
      page: 1,                    // 当前页码
      limit: 10,                  // 每页数
      total: 0,                   // 总条数
      dataListLoading: false,     // 数据列表，loading状态
      dataListSelections: [],     // 数据列表，多选项
      addOrUpdateVisible: false,   // 新增／更新，弹窗visible状态
    }
  },
  created() {
    this.getDataList()
  },
  components: {
    // AddOrUpdate
  },
  methods: {
    // this.dataForm.describe 是指的搜索的关键词
    showDate(val) {
      // let val = this.mdToChineseString(val)
      if (
        val.indexOf(this.dataForm.describe) !== -1 &&
        this.dataForm.describe !== ''
      ) {
        return val.replace(
          this.dataForm.describe,
          '<font color="#f00">' + this.dataForm.describe + '</font>'
        )
      } else {
        return val
      }
    },
    mdToChineseString(md) {
      let reg = /[\u4e00-\u9fa5]/g;
      return md.match(reg).join(''); //过滤出汉字
    },
    showDateC(val1) {
      let val = this.mdToChineseString(val1)
      // console.log(val) 
      if (
        val.indexOf(this.dataForm.describe) !== -1 &&
        this.dataForm.describe !== ''
      ) {
        let hl = val.replace(
          this.dataForm.describe,
          '<font color="#f00">' + this.dataForm.describe + '</font>'
        )
        let start = hl.indexOf(this.dataForm.describe) - 19 - 10 ||0
        let end = hl.length
        // console.log(hl.substring(start, end))
        let sub = hl.substring(start, end) //截取长度
       
        return sub
      } else {
        return val
      }
    },
    // 子级
    childHandle(row) {
      // // console.log(row)
      // 路由参数
      const routeParams = {
        routeName: `${this.$route.name}__${row !== undefined ? row.id : 0}`,
        title: `${this.$route.meta.title}-公告详情`,
        path: 'components/NoticeInfo',
        params: {
          id: row !== undefined ? row.id : 0,
          notice: row,
        }
      }
      // 动态路由
      addDynamicRoute(routeParams, this.$router)
    },
    searchNotice() { //全文模糊查询公告
      if (this.dataForm.describe === null || this.dataForm.describe === '') {
        // console.log('查询条件为空')
        this.hot = 'hot'
        return this.getDataList()
      }
      this.dataListLoading = true
      servicesApi.getNoticeList(this.dataForm.describe).then(res => {
        // console.log(res.data)
        let code = res.data.code
        let data = res.data.data
        if (code === 200) {
          this.dataList = data
          this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
          this.total = data.length
        } else {
          this.dataList = []
          this.showDataList = []
          this.total = 0
        }
        this.dataListLoading = false
        this.index++
        if (this.index>1) {
          this.hot=''
        }
      })
    },
    getDataList: function() {//初始化页面获取所有公告
      // this.dataListLoading = true
      // this.total = this.dataList.length
      // this.dataListLoading = false

      this.dataListLoading = true
      servicesApi.getHomeNotice().then(res => {
        // console.log(res.data)
        let code = res.data.code
        let data = res.data.data
        if (code === 200) {
          this.dataList = data
          this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
          this.total = data.length
        } else {
          this.dataList = []
          this.showDataList = []
          this.total = 0
        }
        this.dataListLoading = false
      })


    },

    // 多选
    dataListSelectionChangeHandle(val) {
      this.dataListSelections = val
    },
    // 排序
    dataListSortChangeHandle(data) {
      // if (!data.order || !data.prop) {
      //   this.order = ''
      //   this.orderField = ''
      //   return false
      // }
      // this.order = data.order.replace(/ending$/, '')
      // this.orderField = data.prop.replace(/([A-Z])/g, '_$1').toLowerCase()
      // this.getDataList()
    },
    // 分页, 每页条数
    pageSizeChangeHandle(val) {
      this.page = 1
      this.limit = val
      // this.getDataList()
      this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
    },
    // 分页, 当前页
    pageCurrentChangeHandle(val) {
      this.page = val
      // this.getDataList()
      this.showDataList = this.dataList.slice((this.page - 1) * this.limit, this.page * this.limit);   // 抓取区间数据
    },

    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 关闭当前窗口
    closeCurrentTab(data) {
      let tabName = this.$store.state.contentTabsActiveName
      this.$store.state.contentTabs = this.$store.state.contentTabs.filter(item => item.name !== tabName)
      if (this.$store.state.contentTabs.length <= 0) {
        this.$store.state.sidebarMenuActiveName = this.$store.state.contentTabsActiveName = 'home'
        return false
      }
      if (tabName === this.$store.state.contentTabsActiveName) {
        this.$router.push({ name: this.$store.state.contentTabs[this.$store.state.contentTabs.length - 1].name })
      }
    },
    // 删除
    deleteHandle(id) {

      let noticeIds = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      // console.log(noticeIds)

      this.$confirm(`确定对[id=${noticeIds.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        servicesApi.deleteNoticeByIds(noticeIds).then(res => {
          if (res.data.code !== 200) {
            return this.$message.error(res.data.msg)
          }
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.getDataList()
            }
          })
        })
      }).catch(() => { })
      // if (this.mixinViewModuleOptions.deleteIsBatch && !id && this.dataListSelections.length <= 0) {
      //   return this.$message({
      //     message: this.$t('prompt.deleteBatch'),
      //     type: 'warning',
      //     duration: 500
      //   })
      // }
      // this.$confirm(this.$t('prompt.info', { 'handle': this.$t('delete') }), this.$t('prompt.title'), {
      //   confirmButtonText: this.$t('confirm'),
      //   cancelButtonText: this.$t('cancel'),
      //   type: 'warning'
      // }).then(() => {
      //   this.$http.delete(
      //     `${this.mixinViewModuleOptions.deleteURL}${this.mixinViewModuleOptions.deleteIsBatch ? '' : '/' + id}`,
      //     this.mixinViewModuleOptions.deleteIsBatch ? {
      //       'data': id ? [id] : this.dataListSelections.map(item => item[this.mixinViewModuleOptions.deleteIsBatchKey])
      //     } : {}
      //   ).then(({ data: res }) => {
      //     if (res.code !== 0) {
      //       return this.$message.error(res.msg)
      //     }
      //     this.$message({
      //       message: this.$t('prompt.success'),
      //       type: 'success',
      //       duration: 500,
      //       onClose: () => {
      //         this.getDataList()
      //       }
      //     })
      //   }).catch(() => {})
      // }).catch(() => { })
    },
    // 导出
    exportHandle() {
      // var params = qs.stringify({
      //   'token': Cookies.get('token'),
      //   ...this.dataForm
      // })
      // window.location.href = `${window.SITE_CONFIG['apiURL']}${this.mixinViewModuleOptions.exportURL}?${params}`
    }
  }
}
</script>
<style scoped>
.hotItem {
  margin-top: 10px;
  /* margin-right: 40px; */
}
</style>
